package com.mqtt.ui.activity;

import android.app.ActionBar;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mqtt.MqttApplication;
import com.mqtt.R;
import com.mqtt.adapter.HomeMqttAdapter;
import com.mqtt.dao.MQTTBean;
import com.mqtt.dao.UpdateMqttConnection;
import com.mqtt.mqtt.MqttConnectionBean;
import com.mqtt.service.IMqttConnectBinder;
import com.mqtt.service.MqttConnectService;
import com.mqtt.ui.base.BaseActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.List;

import butterknife.BindView;
import top.defaults.colorpicker.ColorObserver;
import top.defaults.colorpicker.ColorPickerView;

public class MqttActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemLongClickListener, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.toolbar_base)
    Toolbar mToolbar;
    @BindView(R.id.home_recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.sw_connect_service)
    SwitchCompat mSwConnectServer;

    private HomeMqttAdapter mAdapter;

    private IMqttConnectBinder mIMqttConnectBinder;
    private MqttConnectionBean mSelectServicerBean;

    public class MqttServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIMqttConnectBinder = (IMqttConnectBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }


    @Override
    public String getTitleName() {
        return getString(R.string.app_name);
    }

    @Override
    public boolean showHomeBackMenu() {
        return false;
    }

    @Override
    public void initData() {
        mSwConnectServer.setOnCheckedChangeListener(this);
        mAdapter = new HomeMqttAdapter(R.layout.item_home);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setNewData(MqttApplication.sMQTTListBean);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
        mAdapter.addFooterView(getFooterView());
        mAdapter.addHeaderView(getHeaderView());
        Intent intent = new Intent(this, MqttConnectService.class);
        bindService(intent, new MqttServiceConnection(), BIND_AUTO_CREATE);
        try {
            mToolbar.setTitle(MqttApplication.mMqttConnectionBean.getClientId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home_navigation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.home_add_service) {
            showAddServiceDialog();
            return true;
        } else if (id == R.id.switch_service) {
            showServiceList();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private void showAddServiceDialog() {
        startActivity(new Intent(this, EditConnectionActivity.class));
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, final View view, int position) {
//        if(null == MqttApplication.mMqttConnectionBean || !mIMqttConnectBinder.isConnect()){
//            Toast.makeText(this, "请先连接服务", Toast.LENGTH_SHORT).show();
//            return;
//        }
        MQTTBean mqttBean = mAdapter.getData().get(position);
        if (mAdapter.isShowDeleteIcon()) {
            upColor(mqttBean);
        } else {
            LinearLayout headerLayout = mAdapter.getHeaderLayout();
            headerLayout.findViewById(R.id.current_color_bg).setBackgroundColor(mqttBean.getColor());
            String color = Integer.toHexString(mqttBean.getColor()).toUpperCase();
            color = "[color]" + color.substring(2, color.length());
            mIMqttConnectBinder.onPublish(color);

        }
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        // 长按Item的事件处理
        mAdapter.setShowDeleteIcon(true);
        mAdapter.notifyDataSetChanged();
        LinearLayout footerLayout = mAdapter.getFooterLayout();
        AppCompatButton footerView = footerLayout.findViewById(R.id.btn_add_new_color);
        footerView.setText(getText(R.string.edit_item_done));
        return true;
    }

    public View getFooterView() {
        View footerView = LayoutInflater.from(this).inflate(R.layout.item_home_footerview, null);
        final AppCompatButton btn = footerView.findViewById(R.id.btn_add_new_color);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAdapter.isShowDeleteIcon()) {
                    mAdapter.setShowDeleteIcon(false);
                    btn.setText(getText(R.string.add_new_Color));
                    mAdapter.notifyDataSetChanged();
                } else {
                    upColor(null);// 添加新的颜色
                }
            }
        });
        return footerView;
    }

    /**
     * 更新颜色
     *
     * @param mqttBean 默认显示的color
     */
    private void upColor(MQTTBean mqttBean) {
        boolean newFlag = false;
        if (null == mqttBean) {
            mqttBean = new MQTTBean();
            mqttBean.setColor(Color.RED);
            mqttBean.setColorNickName("");
            mqttBean.setBroker_ip(MqttApplication.mMqttConnectionBean.getBroker_ip());
            newFlag = true;
        }

        View inflate = getLayoutInflater().inflate(R.layout.dialog_color_select, null);
        final TextView tv = inflate.findViewById(R.id.color_bg);
        final TextView colorText = inflate.findViewById(R.id.color_text);
        final TextInputEditText colorName = inflate.findViewById(R.id.et_setup_colot_name);
        final ColorPickerView colorPicker = inflate.findViewById(R.id.colorPicker);
        colorPicker.setInitialColor(mqttBean.getColor());
        String colorNickName = mqttBean.getColorNickName();
        colorName.setText(colorNickName);
        int textLength = TextUtils.isEmpty(colorNickName) ? 0 : colorNickName.length();
        colorName.setSelection(textLength);
        colorPicker.subscribe(new ColorObserver() {
            @Override
            public void onColor(int color, boolean fromUser) {
                tv.setBackgroundColor(color);
                String strColor = "0x" + Integer.toHexString(color);
                colorText.setText(strColor.toUpperCase());
            }
        });
        final MQTTBean finalMqttBean = mqttBean;
        final boolean finalNewFlag = newFlag;
        new AlertDialog.Builder(this)
                .setTitle("选择颜色")
                .setView(inflate)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updataColorData(colorPicker.getColor(), colorName.getText().toString().trim(), finalMqttBean, finalNewFlag);
                    }
                })
                .show();
    }


    /**
     * 更新颜色数据
     *
     * @param color     当前选择的颜色
     * @param colorName 设置的颜色名
     * @param mqttBean  mqttBean
     * @param newFlag   是否是新的数据
     */
    private void updataColorData(int color, String colorName, MQTTBean mqttBean, boolean newFlag) {
        LinearLayout headerLayout = mAdapter.getHeaderLayout();
        headerLayout.findViewById(R.id.current_color_bg).setBackgroundColor(color);
        mqttBean.setColor(color);
        String hexString = Integer.toHexString(color);
        String tmp = "0x" + hexString;
        String str = TextUtils.isEmpty(colorName) ? tmp.toUpperCase() : colorName;
        mqttBean.setColorNickName(str);
        if (newFlag) {
            mAdapter.addData(mqttBean);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mqttBean.save();// 保存到数据库
    }

    /**
     * 添加头View
     *
     * @return
     */
    public View getHeaderView() {
        return LayoutInflater.from(this).inflate(R.layout.item_home_headerview, null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDateCurrentServer(UpdateMqttConnection mqttConnection) {
        // 添加服务后的回调
        MqttConnectionBean mqttConnectionBean = mqttConnection.getMqttConnectionBean();
        mSwConnectServer.setChecked(false);
        List<MQTTBean> data = mAdapter.getData();
        data.clear();
        mAdapter.notifyDataSetChanged();
        List<MQTTBean> mqttBeans = LitePal.where("broker_ip = ?", mqttConnectionBean.getBroker_ip()).find(MQTTBean.class);
        mAdapter.setNewData(mqttBeans);
        LinearLayout headerLayout = mAdapter.getHeaderLayout();
        headerLayout.findViewById(R.id.current_color_bg).setBackgroundColor(Color.WHITE);
        mToolbar.setTitle(mqttConnectionBean.getClientId());
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (null == MqttApplication.mMqttConnectionBean) {
            Toast.makeText(this, "请先添加服务", Toast.LENGTH_SHORT).show();
            mSwConnectServer.setChecked(false);
            return;
        }
        // 点击连接或者断开服务的监听
        if (b) {
            //  连接
            mIMqttConnectBinder.onConnect();
        } else {
            //  断开
            mIMqttConnectBinder.onDisConnect();
        }
    }

    /**
     *  显示服务列表的dialog
     */
    private void showServiceList() {
        List<MqttConnectionBean> connectionBeanList = LitePal.findAll(MqttConnectionBean.class);
        if(null == connectionBeanList && connectionBeanList.size() <= 0){
            Toast.makeText(this, "无更多服务", Toast.LENGTH_SHORT).show();
            return;
        }
        View inflate = getLayoutInflater().inflate(R.layout.dialog_service_select, null);
        RadioGroup rg = inflate.findViewById(R.id.rg_setver_list);
        for (int i = 0; i < connectionBeanList.size(); i++) {
            MqttConnectionBean mqttConnectionBean = connectionBeanList.get(i);
            RadioButton rb = new RadioButton(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(10,10,10,10);
            rb.setLayoutParams(layoutParams);
            rb.setPadding(20, 20, 20, 20);
            String name = mqttConnectionBean.getClientId() + "(" + mqttConnectionBean.getHost() + ":" + mqttConnectionBean.getPort() + ")";
            rb.setText(name);
            if(mqttConnectionBean.equals(MqttApplication.mMqttConnectionBean)){
                rb.setChecked(true);
                mSelectServicerBean = mqttConnectionBean;
                MqttApplication application = (MqttApplication) getApplication();
                application.setmTmpMqttBean(mqttConnectionBean);
            }
            rb.setId(i);
            rg.addView(rb);
        }
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                List<MqttConnectionBean> connectionBeanList = LitePal.findAll(MqttConnectionBean.class);
                mSelectServicerBean = connectionBeanList.get(i);
            }
        });

        new AlertDialog.Builder(this)
                .setTitle("选择连接的服务")
                .setView(inflate)
                .setNegativeButton("编辑", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(EditConnectionActivity.EDIT_FLAG,true);
                        MqttApplication application = (MqttApplication) getApplication();
                        application.setmTmpMqttBean(mSelectServicerBean);
                        startActivity(EditConnectionActivity.class,bundle);
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        MqttApplication.mMqttConnectionBean = mSelectServicerBean;
                    }
                })
                .show();
    }

}
